﻿@using OnWork.DataCenter.BLL.DataCenter;
@using OnWork.DataCenter.DAL.DataCenter;
@using OnWork.DataCenter.Utils.Caches;
@using OnWork.DataCenter.BLL.Standard;
@using SqlSugar;
@inherits ComponentBaseDataCenter;
<div class="row g-3 form-inline">
    <div class="col-12">
        <Select PlaceHolder="请选择数据连接"
                TValue="long"
                IsSelectAllTextOnEnter="true" Items="@Conns" ShowSearch="true"
                ShowLabel="true"
                DisplayText="数据连接" @bind-Value="@Config.DBID" OnSelectedItemChanged="OnSelectedItemChangedAsync" />
    </div>
    <div class="col-12">
        <BootstrapInputGroup>
            <label class="form-label">数据表名</label>
            <Select PlaceHolder="请选择表名"
                    TValue="string"
                    IsSelectAllTextOnEnter="true" @bind-Value="@Config.DBTable" Items="@Tables" ShowSearch="true"
                    ShowLabel="true"
                    DisplayText="数据表名" />
            <Button Text="刷新" IsAsync="true" Icon="fa-solid fa-arrows-rotate" OnClick="@BtnLoadTableAsyncButton" />
        </BootstrapInputGroup>
    </div>
</div>


<Table TItem="DBCol" UseInjectDataService="false" IsPagination="false" DoubleClickToEdit="true"
       IsStriped="true" IsBordered="true" ShowSkeleton="true" IsMultipleSelect="true" ShowEmpty="false" ShowLoading="true" ShowColumnList="true"
       ShowToolbar="true" ShowExtendButtons="true"
       ShowSearch="false" ShowAdvancedSearch="false"
       AutoGenerateColumns="false" EditMode="EditMode.InCell"
       OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync"
       ShowToastAfterSaveOrDeleteModel="false" Items="@Config.DBCols">
    <TableToolbarTemplate>
        <TableToolbarButton TItem="DBCol"
                            Color="Color.Info"
                            Icon="fas fa-bars-staggered"
                            Text="加载表列"
                                        IsAsync OnClickCallback="@BtnLoadColAsyncButton" />
    </TableToolbarTemplate>
    <TableColumns>
        <TableColumn Text="主键" @bind-Field="@context.IsPK" />
        <TableColumn Text="字段名" @bind-Field="@context.ColName" />
        <TableColumn Text="类型" @bind-Field="@context.ColType" />
        <TableColumn Text="DataTable列" @bind-Field="@context.ColSelectToken" />
        <TableColumn Text="说明" @bind-Field="@context.Remark" />
    </TableColumns>
</Table>


    @code {
    /// <summary>
    /// 依赖注入 提示信息
    /// </summary>
    [Inject]
    protected DSDataBaseBLL dBConnBLL { get; set; }

    /// <summary>
    /// 数据库配置
    /// </summary>
    [Parameter]
    public DataBaseConfig Config { get; set; } = new DataBaseConfig();

    /// <summary>
    /// 连接字符串
    /// </summary>
    private List<SelectedItem> Conns;


    /// <summary>
    /// 数据库表名称
    /// </summary>
    private List<SelectedItem> Tables;

    /// <summary>
    /// 数据库连接
    /// </summary>
    private List<DSDataBase> dSDataBases;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        //查询列表
        if (Conns is null)
        {
            dSDataBases = dBConnBLL.GetALL();
            Conns = dSDataBases.Select(x => new SelectedItem() { Text = x.Name, Value = x.ID.ToString() }).ToList();
        }
    }

    /// <summary>
    /// 当选择项目修改时
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    private async Task OnSelectedItemChangedAsync(SelectedItem item)
    {
        try
        {
            var obj = dSDataBases.Where(x => x.ID == long.Parse(item.Value)).FirstOrDefault();
            if (obj != null)
            {

                Config.DBConn = obj.ConnStr; //连接字符串
                Config.DBType = (DbType)obj.Type; //数据库类型
                                                  //var db = SqlSugarCache.GetOrCreate((DbType)obj.Type, obj.ConnStr, obj.ID.ToString());
                                                  //if (db != null)
                                                  //{
                                                  //    var tables = db.DbMaintenance.GetTableInfoList(); //true 走缓存 false不走缓存
                                                  //    if (tables != null)
                                                  //    {
                                                  //        Tables = tables.Select(x => new SelectedItem() { Text = x.Name, Value = x.Name }).ToList();
                                                  //    }

                //}
            }
        }
        catch (Exception ex)
        {
            await base.MessageError(ex.ToString());
        }
    }

    /// <summary>
    /// 加载Table列表按钮
    /// </summary>
    /// <returns></returns>
    private async Task BtnLoadTableAsyncButton()
    {
        try
        {
            //获取数据库请求
            var db = SqlSugarCache.GetOrCreate(Config.DBType, Config.DBConn, Config.DBID.ToString());
            if (db != null)
            {
                var tables = db.DbMaintenance.GetTableInfoList(false); //true 走缓存 false不走缓存
                if (tables != null)
                {
                    Tables = tables.Select(x => new SelectedItem() { Text = x.Name, Value = x.Name }).ToList();
                }
            }
        }
        catch (Exception ex)
        {
            await base.MessageError(ex.ToString());
        }
    }

    /// <summary>
    /// 加载Table 列
    /// </summary>
    /// <returns></returns>
    private async Task BtnLoadColAsyncButton(IEnumerable<DBCol> item)
    {
        try
        {
            //获取数据库请求
            var db = SqlSugarCache.GetOrCreate(Config.DBType, Config.DBConn, Config.DBID.ToString());
            if (db != null)
            {
                var cols = db.DbMaintenance.GetColumnInfosByTableName(Config.DBTable);
                if (cols != null)
                {
                    foreach (var c in cols)
                    {
                        DBCol col = new DBCol()
                            {
                                ColName = c.DbColumnName,
                                IsPK = c.IsIdentity,
                                Remark = c.DataType,
                            };
                        var ishas = Config.DBCols.Where(x => x.ColName == col.ColName).Any();
                        if (ishas == false)
                        {
                            Config.DBCols.Add(col);
                        }
                    }
                }
            }
            base.StateHasChanged();//刷新页面
        }
        catch (Exception ex)
        {
            await base.MessageError(ex.ToString());
        }
    }


    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="item"></param>
    /// <param name="changedType"></param>
    /// <returns></returns>
    private async Task<bool> OnSaveAsync(DBCol item, ItemChangedType changedType)
    {
        //RESTfulResult<object> result;
        if (changedType == ItemChangedType.Update) // 更新
        {
            var entry = Config.DBCols.Where(x => x.id == item.id).FirstOrDefault();
            item.Adapt(entry);
            return await Task.FromResult(true);
        }
        else //新增
        {
            Config.DBCols.Add(item);
            return await Task.FromResult(true);
        }
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="items"></param>
    /// <returns></returns>
    private async Task<bool> OnDeleteAsync(IEnumerable<DBCol> items)
    {
        Config.DBCols.RemoveAll(x => items.Contains(x));
        return await Task.FromResult(true);
    }
}
